<script>
// [Global Scope]
// In a browser, the global scope is the window object. 
// If a variable declaration occurs outside of a function, 
// then that variable exists on the global object.

// it could be referenced as window.x, 
// but because it exists on the global object we can simply refer to it as x.
var x = 9;


// [Local Scope]
// JavaScript also creates a Local Scope inside each function body
function myFunc() {
	var y = 5;
}
// console.log( y ); // ReferenceError: y is not defined

// If you declare a variable and forget to use the var keyword, 
// that variable is automatically made global.
(function () {
	z = 10;
})();
console.log( z );


// Wrapping everything in a function which is then immediately invoked means 
// all the variables within that function are bound to the local scope. 
// At the very end you can then expose all your methods by binding 
// the jQuery object to the window, the global object. 
(function() {
	var jQuery = { /* All my methods go here. */ };
	window.jQuery = jQuery;
})();


function outer() {
	var x = 5;
	function inner() {
		console.log( x );
		var y = 10;
	}
	inner(); // 5
	//console.log( y ); // ReferenceError: y is not defined
}
outer();


//Functions have access to variables defined in the same scope.
var foo = "hello";
var sayHello = function() {
	console.log( foo );
};
sayHello(); // "hello"
console.log( foo ); // "hello"


// Variables with the same name can exist in different scopes with different values:
var foo = "world";
var sayHello = function() {
	var foo = "hello";
	console.log( foo );
};
sayHello(); // "hello"
console.log( foo ); // "world"


// When, within a function, you reference a variable defined in an outer scope, 
// that function can see changes to the variable's value after the function is defined.
var myFunction = function() {
	var foo = "hello";
	var myFn = function() {
		console.log( foo );
	};
	foo = "world";
	return myFn;
};
var f = myFunction();
f(); // "world"


(function() {
	var baz = 1;
	var bim = function() {
		console.log( baz );
	};
	bar = function() {
		console.log( baz );
	};
})();
bar();
// bim(); //bim is not defined outside of the function
//console.log( baz ); // baz is not defined outside of the function
</script>